"""
1) restore data2 original
2) backup de archivos de data2 de chu, en data2 original
3) copia de archivos de data2 a data2 original
4) links a release
5) branch de usuario
"""

DATA2_BACKUP = 'c:\\changeunits\\data2Restore\\%s\\data2'
COPY_CMD = 'echo F | xcopy %s "%s" /S /C /F /R /Y'
import os, sys

def dirwalk(dir):
	"walk a directory tree, using a generator"
	for f in os.listdir(dir):
		fullpath = os.path.join(dir,f)
		if os.path.isdir(fullpath) and not os.path.islink(fullpath):
			for x in dirwalk(fullpath):  # recurse into subdir
				yield x
		else:
			yield fullpath
			
def bkp():
	data2chu = os.path.abspath('.\\data2')
	data2bkp = DATA2_BACKUP % sys.argv[2]
	if not os.path.exists(data2bkp):
		os.mkdir(data2bkp)
	for file in (filter(lambda x: not '.svn' in x, dirwalk(data2chu))):
		src = os.path.join('\\data2',file[len(data2chu)+1:])
		if os.path.exists(src):
			dest = os.path.join(data2bkp,file[len(data2chu)+1:])
			cmd = COPY_CMD % (src,dest)
			print cmd
			os.system(cmd)
	
UPDATE = """UPDATE branches_conn SET branch_id = %s WHERE usuario = '%s';
commit;
exit;
"""
def branch():
	cmd = filter(lambda x: True, os.popen('svn info'))
	nrochu = cmd[1].split('/')[-1].replace('\n','')
	user = os.getenv('username').upper()
	query = UPDATE % (nrochu,user)	
	fil = 'tmp.sql'
	f = open(fil,'w')
	f.write(query)
	f.close()
	cmd = 'sqlplus oraprod/desa9i@desa9i @'+fil.split('.')[0]
	os.system(cmd)
	os.remove(fil)
	print 'brancheando usuario',user,'a chu',nrochu,'...'
	

DICCMD = {'bkp':bkp,'branch':branch}

def main():
	DICCMD[sys.argv[1]]()
	
if __name__ == '__main__':
	main()